import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Goods.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class GoodsPage extends StatefulWidget {
  final String label;

  const GoodsPage({Key key, this.label}) : super(key: key);

  @override
  _GoodsPageState createState() => _GoodsPageState();
}

class _GoodsPageState extends State<GoodsPage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController controller = EasyRefreshController();

  //数据集合
  var _item = [];
  int pageNum = 0;

  @override
  void initState() {
    super.initState();
    _getGoods(true);
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      header: CommWidget.commHeader(),
      footer: CommWidget.commFooter(),
      controller: controller,
      child: StaggeredGridView.countBuilder(
          shrinkWrap: true,
          itemCount: _item.length,
          padding: EdgeInsets.only(left: 8, right: 8, top: 8),
          physics: NeverScrollableScrollPhysics(),
          crossAxisCount: 2,
          mainAxisSpacing: 8,
          crossAxisSpacing: 8,
          staggeredTileBuilder: (index) => StaggeredTile.fit(1),
          itemBuilder: (BuildContext context, int index) {
            return GestureDetector(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: _itemView(context, index),
                ),
                onTap: () {
                  Goods goods = _item[index];
                  String url =
                      '${Routers.PAGE_GOOD_INFO}?goodsId=${goods.goodsId}';
                  Routers.router.navigateTo(context, url,
                      transition: TransitionType.inFromRight);
                });
          }),
      onRefresh: () {
        pageNum = 0;
        _getGoods(true);
      },
      onLoad: () {
        _getGoods(false);
      },
    );
  }

  Widget _itemView(BuildContext context, int index) {
    Goods goods = _item[index];
    Widget _divWidget = Container(
      color: Theme.of(context).dividerColor,
      height: 0.5,
      margin: EdgeInsets.all(8),
    );
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        _picWidget(goods),
        _titleWidget(goods),
        SizedBox(height: 6),
        _disPriceWidget(goods),
        _divWidget,
        _userWidget(goods),
        SizedBox(height: 8),
      ],
    );
  }

  ///图片
  Widget _picWidget(Goods goods) {
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(6)),
      child: ClipRRect(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(6),
          topRight: Radius.circular(6),
          bottomLeft: Radius.circular(0),
          bottomRight: Radius.circular(0),
        ),
        child: CachedNetworkImage(
          imageUrl: Api.getUrl(goods.goodsImg.split(",")[0]),
          fit: BoxFit.cover,
          errorWidget: (context, url, error) => CommWidget.imgError(),
        ),
      ),
    );
  }

  ///商品标题
  Widget _titleWidget(Goods goods) {
    return Container(
      child: Text(
        goods.goodsName,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontWeight: FontWeight.w800),
      ),
      margin: EdgeInsets.only(left: 8),
    );
  }

  ///价格
  Widget _disPriceWidget(Goods goods) {
    bool showPrice = null != goods && null != goods.price && goods.price > 0;
    int buys = null != goods && null != goods.wantNum ? goods.wantNum : 0;
    return Row(crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[
      SizedBox(width: 8),
      Offstage(
        offstage: !showPrice,
        child: Text(
          '￥',
          style: TextStyle(
            color: Color(0xffFA4344),
            fontSize: 12,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
      Text(
        '${showPrice ? goods.price : "免费"}',
        style: TextStyle(
          color: Color(0xffFA4344),
          fontSize: 18,
          fontWeight: FontWeight.w600,
        ),
      ),
      Expanded(flex: 1, child: Container()),
      Text(
        "$buys人想要",
        style: TextStyle(fontSize: 12, color: Colors.grey),
      ),
      SizedBox(width: 8),
    ]);
  }

  ///用户信息
  Widget _userWidget(Goods goods) {
    Widget _headWidget = Container(
      width: 28,
      height: 28,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(6),
        child: CachedNetworkImage(
          imageUrl: Api.getUrl(goods.imgUrl),
          fit: BoxFit.cover,
          errorWidget: (context, url, error) => Image.asset(
            Comm.IMG_DEFAULT,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
    return Row(
      children: <Widget>[
        SizedBox(width: 8),
        _headWidget,
        SizedBox(width: 6),
        Text(
          goods.userName,
          style: TextStyle(
            fontWeight: FontWeight.w800,
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  Future<void> _getGoods(bool isRefresh) async {
    Map<String, String> params = Map();
    params['classtify'] = "${widget.label}";
    params['pageNum'] = '$pageNum';
    params['pageSize'] = '10';
    await Http.get(Api.URL_GOODSLIST, params: params, successCallBack: (data) {
      List list = json.decode(data).map((m) => Goods.fromJson(m)).toList();
      if (isRefresh) {
        controller.finishRefresh();
      } else {
        controller.finishLoad(noMore: null != list && list.length < 10);
      }
      Future.delayed(Duration(milliseconds: 200)).then((e) {
        setState(() {
          if (isRefresh) {
            _item.clear();
          }
          _item.addAll(list);
          pageNum++;
        });
      });
    }, errorCallBack: (msg) {
      if (isRefresh) {
        controller.finishRefresh();
      } else {
        controller.finishLoad();
      }
      Toast.show(msg);
    });
  }

  @override
  bool get wantKeepAlive => true;
}
